<template>
  <div>
    <div class='search'>
        <input class="search-input" type="text" 
           placeholder="输入城市或拼音"
           v-model='keyword'>
    </div>
    <div class="search-content" ref='search' v-show='keyword'>
      <ul>
        <li v-for='item in list' :key='item.id' 
          @click='handleCityClick(item.name)' class='search-item border-bottom'>
          {{item.name}}
        </li>
        <li class="search-item borser-bottom" v-show='hasNoData'>
          没有匹配到数据
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
import { mapState, mapMutations, mapActions } from "vuex";
export default {
  name: "CitySearch",
  props: ["cities"],
  data() {
    return {
      keyword: "",
      list: [],
      timer: null
    };
  },
  mounted() {
    this.scroll = new Bscroll(this.$refs.search);
  },
  computed: {
    hasNoData() {
      return !this.list.length;
    },
    ...mapState(["city"])
  },
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        //节流
        const result = [];
        for (let i in this.cities) {
          this.cities[i].forEach(value => {
            if (
              value.spell.indexOf(this.keyword) > -1 ||
              value.name.indexOf(this.keyword) > -1
            ) {
              result.push(value);
            }
          });
        }
        this.list = result;
      }, 100);
    }
  },
  methods: {
    handleCityClick(city) {
      // this.$store.dispatch("changeCity", city);
      this.changeCity(city);
      this.$router.push("/");
    },
    ...mapActions({
      changeCity: "changeCity"
    })
  },
  components: {}
};
//  html 的font-size设置成了50px 1rem=50px,1px=0.02rem,设计稿是2倍像素
//  设计稿86px,实际写43px,转换就是0.86rem
</script>

<style lang='stylus' scoped>
@import '~styles/variables'
.search
  height 0.72rem
  padding 0 0.1rem
  background $bgColor
  .search-input
    box-sizing border-box
    width 100%
    height 0.62rem
    padding 0 0.1rem
    line-height 0.62rem
    text-align center
    border-radius 0.06rem
    color #666
.search-content
  overflow hidden
  position absolute
  z-index 1
  top 1.58rem
  left 0
  right 0
  top 1.58rem
  bottom 0
  background #eeeeee
  .search-item
    line-height 0.62rem
    padding-left 0.2rem
    background #ffffff
    color #666
</style>
